package com.atguigu.tingshu.user.pattern.impl;

import com.atguigu.tingshu.album.AlbumFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.user.pattern.UserPaidStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author: atguigu
 * @create: 2024-04-23 14:48
 */
@Slf4j
@Component(SystemConstant.ORDER_ITEM_TYPE_TRACK)  //beanid=类名（首字母小写）
public class TrackPaidStrategy implements UserPaidStrategy {

    @Autowired
    UserPaidTrackMapper userPaidTrackMapper;

    @Autowired
    AlbumFeignClient albumFeignClient;

    /**
     * 处理声音购买记录
     *
     * @param userPaidRecordVo
     */
    @Override
    public void handlerPaidRecord(UserPaidRecordVo userPaidRecordVo) {
        log.info("处理声音购买记录");
        //2.处理购买项目类型为：声音 一个订单包含多个声音
        //2.1 根据订单编号查询购买记录判断是否已处理
        LambdaQueryWrapper<UserPaidTrack> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserPaidTrack::getOrderNo, userPaidRecordVo.getOrderNo());
        queryWrapper.last("limit 1");
        queryWrapper.select(UserPaidTrack::getOrderNo);
        Long count = userPaidTrackMapper.selectCount(queryWrapper);
        if (count > 0) {
            return;
        }
        //2.2 创建已购声音对象集合保存
        TrackInfo trackInfo = albumFeignClient.getTrackInfo(userPaidRecordVo.getItemIdList().get(0)).getData();
        for (Long trackId : userPaidRecordVo.getItemIdList()) {
            UserPaidTrack userPaidTrack = new UserPaidTrack();
            userPaidTrack.setOrderNo(userPaidRecordVo.getOrderNo());
            userPaidTrack.setUserId(userPaidRecordVo.getUserId());
            userPaidTrack.setAlbumId(trackInfo.getAlbumId());
            userPaidTrack.setTrackId(trackId);
            userPaidTrackMapper.insert(userPaidTrack);
        }
    }
}
